package com.htfyun.roobofactory.factorytest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.htfyun.roobofactory.BaseActivity;
import com.htfyun.roobofactory.R;
import com.htfyun.roobofactory.config.RooboBuildConfig;
import com.htfyun.roobofactory.htfyunUtils.ExecuteCommand;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by sst on 2018/7/9.
 */

public class SDCardTestActivity extends BaseActivity {

    private TextView txtSdcardInsert;
    private TextView txtSdcardInfo;

    private Button btnPass;
    private Button btnFail;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factorytest_sdcard);

        mContext = this;

        btnPass = (Button) findViewById(R.id.btnPass);
        btnFail = (Button) findViewById(R.id.btnFail);
        btnPass.setOnClickListener(onPassOrFailClickListener);
        btnFail.setOnClickListener(onPassOrFailClickListener);

        btnPass.setVisibility(RooboBuildConfig.FT_ADD_PASS_BTN ? View.VISIBLE : View.GONE);


        txtSdcardInsert = (TextView) findViewById(R.id.txtSdcardInsert);
        txtSdcardInfo = (TextView) findViewById(R.id.txtSdcardInfo);
        txtSdcardInfo.setText("");

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(sdcardReceiver, getIntentFilterOfSDCard());

        updateUIWhileSDCardMounted();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(sdcardReceiver);
    }

    private String getSDCardPath() {
        if (!isSDCardInserted()) {
            return "";
        }

        StorageManager sm = getSystemService(StorageManager.class);

        if (sm == null) {
            return "";
        }


        List<StorageVolume> volList = sm.getStorageVolumes();
        if (volList == null) {
            return "";
        }

        for (StorageVolume vol : volList) {
            if (vol.getState().equals(Environment.MEDIA_MOUNTED)
                    && vol.getDescription(mContext).contains("SD")) {

                try {
                    Method getPath = StorageVolume.class.getMethod("getPath");
                    String path = (String) getPath.invoke(vol);
                    Log.i(TAG, "StoragePath--->" + path);

                    return path;
//
//                    StatFs stat = new StatFs(path);
//
//                    Log.e(TAG, "total size = " + Formatter.formatFileSize(this, stat.getTotalBytes()));
//                    Log.e(TAG, "free size = " + Formatter.formatFileSize(this, stat.getFreeBytes()));

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        return "";

    }
    private boolean isSDCardInserted() {

        StorageManager sm = getSystemService(StorageManager.class);

        if (sm == null) {
            return false;
        }

        List<StorageVolume> volList = sm.getStorageVolumes();
        if (volList == null) {
            return false;
        }

        for (StorageVolume vol : volList) {

            Log.e(TAG, "vol state = " + vol.getState() + ", desc = " + vol.getDescription(mContext));

        }

        for (StorageVolume vol : volList) {
            if (vol.getState().equals(Environment.MEDIA_MOUNTED)
                    && vol.getDescription(mContext).contains("SD")) {

                return true;
            }
        }

        return false;

    }

    private void updateUIWhileSDCardMounted() {

        txtSdcardInsert.setText(R.string.test_sdcard_please_insert);
        txtSdcardInfo.setText("");
        if (!isSDCardInserted()) {
            return;
        }

        String path = getSDCardPath();
        if (TextUtils.isEmpty(path)) {
            return;
        }

        StatFs stat = new StatFs(path);


        txtSdcardInsert.setText(R.string.test_sdcard_inserted);

        txtSdcardInfo.setText(getString(R.string.test_sdcard_info,
                Formatter.formatFileSize(getActivity(), stat.getTotalBytes()),
                Formatter.formatFileSize(getActivity(), stat.getFreeBytes())));

        startAutoPass(R.string.test_sdcard_pass);

    }

    private IntentFilter getIntentFilterOfSDCard() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);

        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);

        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);

        intentFilter.addDataScheme("file");

        return intentFilter;
    }


    private final BroadcastReceiver sdcardReceiver =  new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            Log.e(TAG, "sdcard action = " + action + ", intent.getData() = " + intent.getData());

            updateUIWhileSDCardMounted();

        }
    };


    private void setBtnPassOrFailEnabled(boolean enabled) {
        btnFail.setEnabled(enabled);
        btnPass.setEnabled(enabled);
    }

    private View.OnClickListener onPassOrFailClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btnPass) {

                setResult(RESULT_OK);
                ActivityCompat.finishAfterTransition(getActivity());

            } else if (v == btnFail) {

                setResult(RESULT_CANCELED);
                ActivityCompat.finishAfterTransition(getActivity());

            }
        }
    };
}
